<?php
namespace Home\Controller;

use Think\Controller;
use Think\Exception;
require(dirname(dirname(__FILE__))."/ORG/wx/wxBizMsgCrypt.class.php");
/**
 * @name 公众号消息与事件接收URL  http://wx.eoiyun.com/Home/Event/index/appid/$APPID$
 * @author perry
 * @version 1.0 2015-07-30
 */
class EventController extends Controller {

	
	function _initialize(){
		// $this->checkToken=C('third_check_token');
  //   $this->checkKey=C('third_check_key');
  //   $this->thirdAppid=C('third_app_id');
  //   $this->thirdAppsecret=C('third_app_secret');
  //   $this->sdk = new \Home\ORG\WeixinThirdSDK($this->thirdAppid,$this->thirdAppsecret);
    $this->checkToken=C('third_check_token');
    $this->checkKey=C('third_check_key');
    $this->thirdAppid=C('third_app_id');
    $this->appid=false;
	}

  //奔雷公众号授权给我们三方平台了，他的消息和事件推送到以下方法
  public function wx62d80f930f7b9382_event(){
    $this->index('wx62d80f930f7b9382');
  }

  //万代公众号授权给我们三方平台了，他的消息和事件推送到以下方法
  public function wxbc19271ec734d5c7_event(){
    $this->index('wxbc19271ec734d5c7');
  }

  //微信自动化测试专用公众号在我们全网发布时会授权我们做测试，他的消息和事件推送到以下方法
  public function wx570bc396a51b8ff8_event(){
    $this->index('wx570bc396a51b8ff8');
  }

  //所有不同appid的公众号消息与事件最终都由此接收入口进入
	private function index($appid) {
    //$appid=$_GET['appid'];
    if(!$appid){
      return;
    }
    $this->appid=$appid;
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    if(!$postStr){
      // echo 'emtpy';
      // M('weixin_xml')->data(array('create_time' => time(), 'content' => 'empty'))->add(); //保存数据
      return;
    }
    $sdkCrypt = new \Home\ORG\wx\WXBizMsgCrypt($this->checkToken,$this->checkKey,$this->thirdAppid);
    $msg='';
    $re=$sdkCrypt->decryptMsg($_REQUEST['msg_signature'], $_REQUEST['timestamp'], $_REQUEST['nonce'], $postStr, $msg);
    
    $request_info=json_encode($_REQUEST);
    M('weixin_xml')->data(array('create_time' => time(), 'content' => $postStr.$request_info,'decrypt_content'=>$msg))->add(); //保存数据
    if($re!=0){
      //解密失败了
      return;
    }
    $postArr=xmlToArray($msg);
    if(array_key_exists('MsgType', $postArr)){
      call_user_func(array($this,$postArr['MsgType']),$postArr);
    }
    //todo 其它事件
    echo "success";
  }

  //接受事件推送  https://mp.weixin.qq.com/wiki/2/5baf56ce4947d35003b86a9805634b1e.html
  //以下是关注事件的推送postArr
  // <xml><ToUserName><![CDATA[gh_d0799ba24a58]]></ToUserName>
  // <FromUserName><![CDATA[o2_qyjsnw0NL5m2EEaLiB2X6INAU]]></FromUserName>
  // <CreateTime>1488345771</CreateTime>
  // <MsgType><![CDATA[event]]></MsgType>
  // <Event><![CDATA[subscribe]]></Event>
  // <EventKey><![CDATA[]]></EventKey>
  // </xml>
  private function event($postArr){
    if($this->appid=='wx570bc396a51b8ff8'){
      //weixin 全网发布测试专用代码
      $reText=$this->transmitText($postArr,$postArr['Event']."from_callback");
      $this->encrypt_response($reText);
      exit;
      //end weixin 全网发布测试专用代码
    }
    
    if(array_key_exists('Event', $postArr)){
      try {
        call_user_func(array($this,$postArr['Event']),$postArr);
        
      } catch (\Exception $e) {
        echo "";
      }
      
    }
    else {
      //TODO what?
      echo "";
    }
  }

  private function text($postArr){
    // M('weixin_xml')->data(array('create_time' => time(), 'content' => '96','decrypt_content'=>json_encode($postArr)))->add(); //保存数据
    if(array_key_exists('Content', $postArr)){
      //weixin 全网发布测试专用代码
      if($postArr['Content']=='TESTCOMPONENT_MSG_TYPE_TEXT'){
        $reText=$this->transmitText($postArr,"TESTCOMPONENT_MSG_TYPE_TEXT_callback");
         M('weixin_xml')->data(array('create_time' => time(), 'content' => '108','decrypt_content'=>$reText))->add(); //保存数据
        $this->encrypt_response($reText);
        exit;
      }
      else if ($this->appid=='wx570bc396a51b8ff8' && stripos("QUERY_AUTH_CODE:", $postArr['Content'])!==false){
        $query_auth_code=str_ireplace("QUERY_AUTH_CODE:", "", $postArr['Content']);
        M('weixin_xml')->data(array('create_time' => time(), 'content' => '119','decrypt_content'=>$query_auth_code))->add(); //保存数据
        $sendoid=$postArr['FromUserName'];
        //file_put_contents($_SERVER['DOCUMENT_ROOT']."/Uploads/QUERY_AUTH_CODE.txt", $query_auth_code.",,,".$sendoid);
        ////echo 'success';
        //exit;
        $thirdAppid=C('third_app_id');
        $thirdAppsecret=C('third_app_secret');
        $sdk = new \Home\ORG\WeixinThirdSDK($thirdAppid,$thirdAppsecret);
        $pj=$sdk->getPingju($query_auth_code);
        M('weixin_xml')->data(array('create_time' => time(), 'content' => '132','decrypt_content'=>json_encode($pj)))->add(); //保存数据
        $body=array();
        // $body['access_token']=$pj['authorization_info']['authorizer_access_token'];
        $body['touser']=$sendoid;
        $body['msgtype']='text';
        $body['text']=array();
        $body['text']['content']=$query_auth_code."_from_api";
        M('weixin_xml')->data(array('create_time' => time(), 'content' => '138','decrypt_content'=>json_encode($body)))->add();
        $re=$sdk->sendMessage(json_encode($body),$this->appid,$pj['authorization_info']['authorizer_access_token']);
        M('weixin_xml')->data(array('create_time' => time(), 'content' => '144','decrypt_content'=>json_encode($re)))->add(); //保存数据
        echo '';
        exit;
      }
      //end weixin 全网发布测试专用代码
      echo "success";
      exit;
    }
    else {
      //TODO what?
      if($this->appid=='wx570bc396a51b8ff8'){
        $reText=$this->transmitText($postArr,"收到了你的无content消息");
        echo $reText;
        exit;
      }
      else {
        echo "success";
      }
    }
  }

  // public function QUERY_AUTH_CODE(){
  //   try {
      
    
  //   $QUERY_AUTH_CODE=file_get_contents($_SERVER['DOCUMENT_ROOT']."/Uploads/QUERY_AUTH_CODE.txt");
  //   if($QUERY_AUTH_CODE){
  //     $tmparr=explode(",,,", $QUERY_AUTH_CODE);
  //     $QUERY_AUTH_CODE=$tmparr[0];
  //     $ToUser=$tmparr[1];
  //     $thirdAppid=C('third_app_id');
  //     $thirdAppsecret=C('third_app_secret');
  //     $sdk = new \Home\ORG\WeixinThirdSDK($thirdAppid,$thirdAppsecret);
  //     $pj=$sdk->getPingju($QUERY_AUTH_CODE);
  //     $body=array();
  //     $body['access_token']=$pj['authorizer_access_token'];
  //     $body['touser']=$ToUser;
  //     $body['msgtype']='text';
  //     $body['content']=$QUERY_AUTH_CODE."_from_api";
  //     $re=$sdk->sendMessage($body);
  //     dump($re);
  //   }
  //   } catch (\Exception $e) {
  //     dump($e->getCode());
  //     dump($e->getMessage());
  //   }
  // }

  //用户关注事件
  //以下是关注事件的推送postArr
  // <xml><ToUserName><![CDATA[gh_d0799ba24a58]]></ToUserName>
  // <FromUserName><![CDATA[o2_qyjsnw0NL5m2EEaLiB2X6INAU]]></FromUserName>
  // <CreateTime>1488345771</CreateTime>
  // <MsgType><![CDATA[event]]></MsgType>
  // <Event><![CDATA[subscribe]]></Event>
  // <EventKey><![CDATA[]]></EventKey>
  // </xml>
  private function subscribe($postArr){
    // //TODO 加密后回复服务器
    // $reText=$this->transmitText($postArr,'欢迎您关注奔雷.');
    // //debug
    // //M('weixin_xml')->data(array('create_time' => time(), 'content' => $reText,'decrypt_content'=>'subscribe response text'))->add();
    // //无需加密回复 ，只要普通回复即可
    // //$this->encrypt_response($reText);
    //   echo $reText;
    //如果数据库里存在用户信息则把subscribe字段设为1，否则添加数据
      $map = array();
      $map['openid'] = $postArr['FromUserName'];
      $map['appid'] = $this->appid;
      $subscribe = M('weixin_user')->where($map)->field('id')->find();

      if ($subscribe) {
          $data = array();
          $data['subscribe'] = 1;
          $data['update_time'] = time();
          $save = M('weixin_user')->where('id='.$subscribe['id'])->save($data);
      } else {
          // import('@.ORG.WeixinSDK');
          // $WeixinSDK = new WeixinSDK();
          // $data = $WeixinSDK->userInfo($object->FromUserName);
          $map['subscribe'] = 1;
          $map['create_time'] = time();
          $data['update_time'] = $map['create_time'];
          $save = M('weixin_user')->add($map);
      }
      //用户信息保存或者更新成功后操作
      // if ($save) {
          //通过扫描二维码进入的，做相应的判断
          if (isset($postArr['Ticket'])) {
              $scene_id = str_replace('qrscene_', '', $postArr['EventKey']);
              $data['qrcode_id'] = $scene_id;
              $data['openid'] = trim($map['openid']);
              $data['appid'] = trim($map['appid']);
              // $data['ticket'] = trim($postArr['Ticket']);
              $data['create_time'] = time();
              M('weixin_qrcode_id')->add($data);
          }
          //回复定义好的关注后回复
          //$contentStr = $this->getData('event', 'subscribe');
          // $reText=$this->transmitText($postArr,'success');
          // $this->encrypt_response($reText);
          echo "";
      // }
  }

  private function SCAN($postArr){
      $map = array();
      $map['openid'] = $postArr['FromUserName'];
      $map['appid'] = $this->appid;
      $subscribe = M('weixin_user')->where($map)->field('id')->find();

      if ($subscribe) {
          $data = array();
          $data['subscribe'] = 1;
          $data['update_time'] = time();
          $save = M('weixin_user')->where($map)->save($data);
      } else {
          $map['subscribe'] = 1;
          $map['create_time'] = time();
          $save = M('weixin_user')->add($map);
      }
      //用户信息保存或者更新成功后操作
      // if ($save) {
          //通过扫描二维码进入的，做相应的判断
          if (isset($postArr['Ticket'])) {
              $scene_id = str_replace('qrscene_', '', $postArr['EventKey']);
              $data['qrcode_id'] = $scene_id;
              $data['openid'] = trim($map['openid']);
              $data['appid'] = trim($map['appid']);
              // $data['ticket'] = trim($postArr['Ticket']);
              $data['create_time'] = time();
              M('weixin_qrcode_id')->add($data);
          }
          //回复定义好的关注后回复
          //$contentStr = $this->getData('event', 'subscribe');
          // $reText=$this->transmitText($postArr,'success');
          // $this->encrypt_response($reText);
          echo "";
      // }
  }

  private function encrypt_response($text){
    $pc = new \Home\ORG\wx\WXBizMsgCrypt($this->checkToken,$this->checkKey,$this->thirdAppid);
    $encryptMsg = '';
    $errCode = $pc->encryptMsg($text, $_REQUEST['timestamp'], $_REQUEST['nonce'], $encryptMsg);
    if ($errCode == 0) {
      //debug
      //M('weixin_xml')->data(array('create_time' => time(), 'content' => $encryptMsg,'decrypt_content'=>'ok response'))->add();
      echo $encryptMsg;
    } else {
      //TODO 错误处理
      //debug
      //M('weixin_xml')->data(array('create_time' => time(), 'content' => $errCode,'decrypt_content'=>'fail response'))->add();
    }
  }

  //用户取消关注事件
  //以下是关注事件的推送postArr
// <xml><ToUserName><![CDATA[gh_76c905174072]]></ToUserName>
// <FromUserName><![CDATA[oYt1Ds5hHn8Cnooctg33MU-FNKbI]]></FromUserName>
// <CreateTime>1499655686</CreateTime>
// <MsgType><![CDATA[event]]></MsgType>
// <Event><![CDATA[unsubscribe]]></Event>
// <EventKey><![CDATA[]]></EventKey>
// </xml>
  private function unsubscribe($postArr){
    //记录用户取关时间
    //如果数据库里存在用户信息则把subscribe字段设为-1，否则添加1条subscribe=-1的数据
      $map = array();
      $map['openid'] = $postArr['FromUserName'];
      $map['appid'] = $this->appid;
      $exist = M('weixin_user')->where($map)->field('id')->find();

      if ($exist) {
          $data = array();
          $data['update_time'] = time();
          $data['subscribe'] = -1;
          $save = M('weixin_user')->where('id='.$exist['id'])->save($data);
          //debug
          M('weixin_xml')->data(array('create_time' => time(), 'content' => '315','decrypt_content'=>M('weixin_user')->getLastSql()))->add(); 
      } else {
          $map['subscribe'] = -1;
          $map['create_time'] = time();
          $map['update_time'] = $map['create_time'];
          $save = M('weixin_user')->add($map);
      }
    echo "";
  }

  //文本消息的回复实现
  private function transmitText($object, $content) {
    $msgType = 'text';
    // //perry add 2015-05-06 如果返回消息是默认消息，则接入多客服系统
    // if(($content == $this->default_response_text)||($content == $this->default_response_text_in_db)){
    //   $msgType = 'transfer_customer_service';
    // }
    $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[%s]]></MsgType>
    <Content><![CDATA[%s]]></Content>
    </xml>";
    $result = sprintf($textTpl, $object['FromUserName'], $object['ToUserName'], time(), $msgType, $content);
    return $result;
    }

  

}